package com.hue.springbootmybatis.plugins;

import com.hue.springbootmybatis.domain.Page;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 姚凤桥
 * @Date: 2022/5/13 21:38
 * @Description: 自定义mybatis分页插件
 */
@Component
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class PagePlugins implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //目标方法之前...
        Object[] args = invocation.getArgs();
        int curPage = 1;
        int pageSize = 10;
        for (Object arg : args) {
            if (arg instanceof Page) {
                Page page = (Page) arg;
                curPage = page.getPage();
                pageSize = page.getSize();
                break;
            }
        }
        //执行目标方法
        List<Object> res = (ArrayList<Object>) invocation.proceed();
        //目标方法之后...
        return res.subList((curPage - 1) * pageSize, Math.min(curPage * pageSize, res.size()));
    }
}
